import { memo, useMemo } from "react";
import { useAtom, useAtomValue } from "jotai";
import { clsxm } from "shared/helpers";
import { IEventItem } from "@/lib/types";
import EventsInfoBalls from "./EventsInfoBalls";
import { viewModelAtom } from "@/store/viewModel";
import ClockIcon from "@/assets/icons/clock.svg?jsx";
import CategoryIcon from "@/assets/icons/category.svg?jsx";
import LightIcon from "@/assets/icons/light.svg?jsx";
import { filterPersonAtom } from "@/store/filterPerson";
import { eventsAtom } from "@/store/events";

export default memo(ToolBar);

function ToolBar() {
  const events = useAtomValue(eventsAtom);
  const [viewModel, setViewModel] = useAtom(viewModelAtom);
  const [filterPerson, setFilterPerson] = useAtom(filterPersonAtom);

  const top3Person = useMemo(() => {
    const map = new Map<string, number>();
    events.forEach((event) => {
      event.people?.forEach((person) => {
        if (!map.has(person)) {
          map.set(person, 0);
        }
        map.set(person, map.get(person) + 1);
      });
    });
    return Array.from(map.entries())
      .sort((a, b) => b[1] - a[1])
      .map((item) => item[0])
      .slice(0, 3);
  }, [events]);

  return (
    <div className="flex items-center bg-[#077077]/[0.07] py-3 text-sm">
      <div className="flex-none px-4">
        <button
          onClick={() => setViewModel("timeline")}
          className={clsxm(
            "mr-3 inline-flex items-center gap-x-1 text-[#077741]/60",
            viewModel === "timeline" && "text-[#077741]",
          )}
        >
          <ClockIcon />
          时间轴
        </button>
        <button
          onClick={() => setViewModel("events")}
          className={clsxm(
            "inline-flex items-center gap-x-1 text-[#077741]/60",
            viewModel === "events" && "text-[#077741]",
          )}
        >
          <CategoryIcon />
          事件类型
        </button>
      </div>
      <EventsInfoBalls />
      {top3Person.length > 0 && (
        <div className="flex flex-none items-center px-4">
          <LightIcon height={24} width={24} />
          {top3Person.map((person, index) => (
            <button
              className={clsxm(
                "ml-2 rounded-full bg-[#CBDBCA] px-2.5 py-0.5 text-[10px] text-[#0B9682]",
                filterPerson === person && "bg-[#0B9682] text-white",
              )}
              key={person}
              onClick={() => {
                filterPerson === person
                  ? setFilterPerson("")
                  : setFilterPerson(person);
              }}
            >
              {person}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
